<template>
    <div v-show="initShow && isUseDraw" class="layout">
        <div v-if="authInfo?.is_set_mini != 2 && authInfo?.is_set_official != 2" class="title_warn">
            <el-icon color="#FAAD14"><WarningFilled /></el-icon>
            <span>抽奖活动需要授权公众号或者营销小程序，请先授权公众号或者配置小程序</span>
        </div>
        <div class="lucky_draw_container">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                :row-key="getRowKeys"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @dataChange="dataChange"
                @select="onSelect"
                @select-all="onSelectAll">
                <template #headerOperateLeft>
                    <!-- 注意 注意 注意  此处和 新建活动按钮 有关联 -->
                    <div class="shareAccountConfiguration">
                        <ShareAccountConfiguration :type="8" @auth="auth" />
                    </div>
                </template>
                <template #headerOperate>
                    <el-dropdown @command="handleCommand">
                        <el-button :disabled="selectId.length == 0">批量操作</el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="item in batchBtn" :key="item.id" :command="item.id">
                                    {{ item.text }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button
                        v-auth="'ADD'"
                        :disabled="authInfo?.is_set_mini != 2 && authInfo?.is_set_official != 2"
                        type="primary"
                        style="margin-left: 10px"
                        @click="toCreateActivity">
                        新建活动
                    </el-button>
                </template>
            </ZwTable>
        </div>
    </div>
    <NoData v-show="initShow && !isUseDraw" @submit="goUse"></NoData>
    <ZwDialog :app-dialog="appDialog">
        <p class="msg">{{ msg }}</p>
    </ZwDialog>
    <Impower ref="impowerRef" :min-app-info="minAppInfo" @submit="submitWxConfig" />
    <ZwOfficialAccounts ref="officialRef" @submit="getSelect" />

    <ShareConfiguration
        v-if="isShowConfiguration"
        ref="shareConfigurationRef"
        v-model:show="isShowConfiguration"
        :activity_id="content_id"
        :account-type="accountType"
        :type="8" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SMART_MARKETING_DRAINAGE_LUCKY_DRAW' });
</script>

<script setup lang="tsx">
import { ref, reactive, computed, nextTick, onActivated } from 'vue';
import useClipboard from 'vue-clipboard3';
import { useRouter } from 'vue-router';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { WarningFilled, Picture as IconPicture } from '@element-plus/icons-vue';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZwDialog from '@/components/Dialog.vue';
import ZwOfficialAccounts from '@/components/ZwOfficialAccounts.vue';
import Impower from './components/Impower.vue';
import NoData from './components/NotData.vue';
import ShareAccountConfiguration from '@/components/common/ShareAccountConfiguration.vue';
import ShareConfiguration from '@/components/common/ShareConfiguration.vue';
import {
    getList,
    isChoose,
    changeStatus,
    dele,
    download,
    setConfig,
    setPublic,
    getMinApp
} from '@/api/smartMarketing/newLottery';
import { getCreateList } from '@/api/common';

import { downloadByBlob, getSetionId } from '@/utils/utils';
import { StatusColor, DOWLOAD_FILE } from '@/utils/smartMarketing';
import { deepCopy } from '@/utils/helper';
import { useStore } from '@/store';
const store = useStore();

const { toClipboard } = useClipboard();
const router = useRouter();
const tableRef = ref();
const impowerRef = ref();
const officialRef = ref();
const selectId = ref([]);
const configInfo = ref();
const minAppInfo = ref();
const isUseDraw = ref(false);
const initShow = ref(false);
const targetArr = reactive([]);
const tableList = ref([]);
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const msg = ref<string>('');
const isShowConfiguration = ref<boolean>(false);
const content_id = ref<number>(0);
const accountType = ref<number>(2);
const shareConfigurationRef = ref<HTMLElement>();
const authInfo = ref<any>(null);
let handleId = reactive({
    btnId: 0,
    rowId: []
});
const btnList = reactive([
    { id: 1, text: '查看', auth: 'LOOK' },
    { id: 2, text: '开始', auth: 'SWITCH' },
    { id: 3, text: '结束', auth: 'SWITCH' },
    { id: 4, text: '编辑', auth: 'EDIT' },
    { id: 5, text: '分享', auth: 'SHARE' },
    { id: 6, text: '统计', auth: 'STATISTICS' },
    { id: 7, text: '复制', auth: 'COPY_LINK' },
    { id: 8, text: '删除', auth: 'DEL' }
]);
const batchBtn = reactive([
    { id: 1, text: '批量开始' },
    { id: 2, text: '批量结束' },
    { id: 3, text: '批量下载' },
    { id: 4, text: '批量删除' }
]);
const defaultParams = {
    title: '',
    created_uid: '',
    created_at: [],
    status: 0,
    type: ''
};
const getRowKeys = (row: any) => {
    return row.id;
};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '活动搜索',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入活动标题'
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_at',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '活动状态',
            name: 'status',
            type: 'select',
            clearable: false,
            placeholder: '请选择',
            optionList: [
                { name: '全部', id: 0 },
                { name: '未开始', id: 1 },
                { name: '进行中', id: 2 },
                { name: '已结束', id: 3 },
                { name: '提前结束', id: 4 }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '活动类型',
            name: 'type',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部类型', id: 0 },
                        // { name: '普通抽奖', id: 1 },
                        // { name: '引流抽奖', id: 2 },
                        { name: '裂变抽奖', id: 3 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        minWidth: 180
    },
    {
        label: '二维码',
        align: 'center',
        minWidth: 120,
        render({ row }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <>
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        src={row.qr_code_link}
                        style="width: 48px; height: 48px; font-size: 49px"
                        vSlots={{ error: slotError }}
                    />
                </>
            );
        }
    },
    {
        label: '活动类型',
        width: 80,
        render({ row }) {
            return (
                <>
                    <p vShow={row.type == 1}>普通抽奖</p>
                    <p vShow={row.type == 2}>引流抽奖</p>
                    <p vShow={row.type == 3}>裂变抽奖</p>
                    <p vShow={row.type == null}>--</p>
                </>
            );
        }
    },
    {
        prop: 'part_num',
        label: '参与人数',
        width: 80
    },
    {
        prop: 'win_num',
        label: '中奖人数',
        width: 80
    },
    {
        label: '状态',
        width: 100,
        render({ row, column, index }) {
            return <span style={StatusColor(row.status, 'obj')?.color}>{StatusColor(row.status, 'obj')?.name}</span>;
        }
    },
    {
        label: '创建人',
        width: 100,
        render({ row }) {
            return <p>{row.created_uid_name || '--'}</p>;
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 170
    },
    {
        prop: 'effective_time',
        label: '有效期',
        width: 350,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <span>{row.begin_date}</span>
                            <span>～</span>
                            <span>{row.end_date}</span>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return (
                <>
                    {filterBtn(row.status).map((item: any) => {
                        return (
                            <ElButton size="small" vAuth={item.auth} onClick={() => handleClick(row, item.id)}>
                                {item.text}
                            </ElButton>
                        );
                    })}
                </>
            );
        }
    }
];
const dataChange = (res: any) => {
    if (res.data) initShow.value = true;

    const currentCorp = store.getters['user/getCurrentCorp'];
    const isUser = JSON.parse(localStorage.getItem('zw-isDraw'));
    if (res.data.length == 0) {
        if (isUser && isUser == currentCorp) {
            isUseDraw.value = true;
        } else {
            isUseDraw.value = false;
        }
    } else {
        isUseDraw.value = true;
    }
};

const auth = (val: any) => {
    !!val && (authInfo.value = val);
};

const filterBtn = (type: any) => {
    let arr: any = [];
    switch (type) {
        case 1:
            arr = [2, 4, 5, 7, 8];
            break;
        case 2:
            arr = [3, 4, 5, 6, 7];
            break;
        case 3:
        case 4:
            arr = [6, 7, 8];
            break;
    }
    const res = btnList.filter((item: any) => arr.includes(item.id));
    return res;
};

const search = (data: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = data;
    state.searchParams = { ...defaultParams, ...data };
};
const reset = (data: any) => {
    tableRef.value?.clearSelection();
    Object.assign(defaultParams, data);
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};

const getChoose = () => {
    isChoose().then((res: any) => {
        configInfo.value = res;
    });
};
getChoose();

const onSelect = (selection: any) => {
    selectId.value = getSetionId('id', selection);
};

const onSelectAll = (selection: any) => {
    selectId.value = getSetionId('id', selection);
};

const setWxConfig = () => {
    getMinApp().then((res: any) => {
        minAppInfo.value = res;
        impowerRef.value.isShow = true;
    });
};
const submitWxConfig = (data: any) => {
    setConfig(data)
        .then(() => {
            ElMessage.success('配置成功！');
            getChoose();
            impowerRef.value.cancelHandel();
        })
        .catch(() => {
            impowerRef.value.cancelHandel();
        });
};

const openPublic = () => {
    officialRef.value.tabIndex = configInfo.value.official_account_id;
    officialRef.value.isShow = true;
};
const getSelect = (data: any) => {
    setPublic({ official_account_id: data.id }).then(() => {
        getChoose();
        ElMessage.success('设置成功！');
    });
};
const handleCommand = (command: string | number | object) => {
    switch (command) {
        case 1:
            handleClick(null, 2, 1);
            break;
        case 2:
            handleClick(null, 3, 1);
            break;
        case 3:
            handleDownload(selectId.value);
            break;
        case 4:
            handleClick(null, 8, 1);
            break;
    }
};

const handleStatus = (type: number, arr: any) => {
    changeStatus({ change_type: type, activity_id: arr }).then(() => {
        cancelHandel('操作成功！', 1);
        tableRef.value?.clearSelection();
    });
};

const handleDel = (arr: any) => {
    dele({ activity_id: arr }).then(() => {
        cancelHandel('操作成功！', 1);
        tableRef.value?.clearSelection();
    });
};
const handleDownload = async (arr: any) => {
    const res = await download({ activity_id: arr });
    DOWLOAD_FILE(res.url, res.name);
    tableRef.value?.clearSelection();
};

const handleCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const cancelHandel = (msg: string, refresh = 0) => {
    if (refresh != 0 && refresh) {
        ElMessage.success(msg);
        selectId.value = [];
        reset(state.searchParams);
    }
    appDialog.visible = false;
};
const submitHandel = () => {
    switch (handleId.btnId) {
        case 2:
            handleStatus(1, handleId.rowId);
            break;
        case 3:
            handleStatus(2, handleId.rowId);
            break;
        case 8:
            handleDel(handleId.rowId);
            break;
    }
};

const handleClick = (row: any, btnIndex: number, isBatch = 0) => {
    handleId = { btnId: btnIndex, rowId: isBatch != 0 ? selectId.value : [row.id] };
    switch (btnIndex) {
        case 1:
            // eslint-disable-next-line no-case-declarations
            const res1 = { type: 'look', id: row.id };
            router.push({ path: '/smartMarketing/drainage/luckyDraw/detail', query: res1 });
            break;
        case 2:
            msg.value = '确定开始所选内容吗？';
            appDialog.title = '开始提醒';
            appDialog.visible = true;
            break;
        case 3:
            msg.value = '确定结束所选内容吗？';
            appDialog.title = '结束提醒';
            appDialog.visible = true;
            break;
        case 4:
            // eslint-disable-next-line no-case-declarations
            const res2 = {
                type: 'edit',
                status: row.status,
                xcx: authInfo.value.is_set_mini,
                official: authInfo.value.is_set_official,
                id: row.id
            };
            router.push({ path: '/smartMarketing/drainage/luckyDraw/detail', query: res2 });
            break;
        case 5:
            accountType.value = row.activity_form;
            content_id.value = row.id;
            isShowConfiguration.value = true;
            break;
        case 6:
            router.push({ path: '/smartMarketing/drainage/luckyDraw/statistics', query: { id: row.id } });
            break;
        case 7:
            // eslint-disable-next-line no-case-declarations
            const res3 = {
                type: 'copy',
                status: row.status,
                xcx: authInfo.value.is_set_mini,
                official: authInfo.value.is_set_official,
                id: row.id
            };
            router.push({ path: '/smartMarketing/drainage/luckyDraw/detail', query: res3 });
            break;
        case 8:
            appDialog.title = '删除提醒';
            msg.value = '确定删除所选内容吗？';
            appDialog.visible = true;
            break;
    }
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '',
    width: '460px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const fetchApi = () => {
    getTableH();
    return new Promise((resolve: any): any => {
        const page_size: string | number = 15;
        const params = { page_size };
        resolve([params, getList]);
    });
};
const toCreateActivity = () => {
    router.push({
        path: '/smartMarketing/drainage/luckyDraw/detail',
        query: {
            xcx: authInfo.value.is_set_mini,
            official: authInfo.value.is_set_official
        }
    });
};

const goUse = (data: number | string) => {
    localStorage.setItem('zw-isDraw', JSON.stringify(data));
    tableRef.value?.reload();
};

onActivated((val: any) => {
    tableRef.value?.clearSelection();
    getChoose();
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>

<style lang="scss" scoped>
.layout {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 142px);
    box-sizing: border-box;
    overflow: hidden;

    .lucky_draw_container {
        flex: 1;
        padding: 24px;
        border-radius: 4px;
        border: 1px solid #eaeaea;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }

    .title_warn {
        background: #fffbe6;
        border-radius: 2px;
        border: 1px solid #ffe58f;
        padding: 9px 17px;
        display: flex;
        align-items: center;

        span {
            font-size: 14px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: rgb(0 0 0 / 65%);
            margin-left: 8px;
        }
    }

    .wxConfig {
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #33302d;
        line-height: 14px;
        display: flex;
        align-items: center;

        .icon {
            width: 16px;
            height: 16px;
            margin-right: 4px;
        }

        .text {
            color: #ff6b00;
            cursor: pointer;
        }

        &:first-of-type {
            margin-right: 24px;
        }
    }
}

.msg {
    text-align: center;
    padding: 50px 0;
}
</style>
